package com.shuai.user.service.impl;

import cn.hutool.json.JSONUtil;
import com.shuai.clientsdk.client.BaixsAPIClient;
import com.shuai.clientsdk.exc.OpenAPIException;
import com.shuai.common.constant.AuthenticationConstant;
import com.shuai.common.constant.ErrorCode;
import com.shuai.common.constant.UserConstant;
import com.shuai.common.exception.BusinessException;
import com.shuai.common.utils.MyJWTUtil;
import com.shuai.user.domain.entity.InterfaceInfo;
import com.shuai.user.domain.entity.User;
import com.shuai.user.domain.request.OnLineInvokeRequest;
import com.shuai.user.service.InterfaceInfoService;
import com.shuai.user.service.OnlineInvokeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class OnlineInvokeServiceImpl implements OnlineInvokeService {


    @Autowired
    private InterfaceInfoService interfaceInfoService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void validatorParams(OnLineInvokeRequest request) {
        if (request == null ||
                request.getId() == null || request.getId() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo byId = interfaceInfoService.getById(request.getId());
        if (byId == null || byId.getApiStatus() != 1) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口状态异常");
        }
    }

    @Override
    public Object onlineInvoke(String authentication, OnLineInvokeRequest invokeRequest) throws OpenAPIException {
        Object payLoadItem = MyJWTUtil.getPayLoadItem(authentication, AuthenticationConstant.PAYLOAD_USERID);
        if (payLoadItem == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户信息异常");
        }
        String userJson = stringRedisTemplate.opsForValue().get(UserConstant.USER_ATTRIBUTE_REDIS_KEY + payLoadItem);
        User user = JSONUtil.toBean(userJson, User.class);
        InterfaceInfo byId = interfaceInfoService.getById(invokeRequest);
        if (byId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口不存在");
        }
        String apiUrl = byId.getApiUrl();
        BaixsAPIClient tempAPIClient = new BaixsAPIClient(user.getApiKey(), user.getApiSecret());
        return tempAPIClient.onlineInvokeTest(apiUrl, invokeRequest.getRequestString());
    }
}
